package com.dianmi.seckill.common.utils;

import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.function.Function;

/**
 * @author xieqiaofu
 * @date 2020/12/4
 */
public class CalculateUtils {

    public static <T> Integer sumByField(List<T> list, Function<T, Integer> function) {
        if (CollectionUtils.isEmpty(list)) {
            return 0;
        }
        int total = 0;
        for (T t : list) {
            Integer number = function.apply(t);
            total += (number == null ? 0 : number);
        }
        return total;
    }

    public static <T> BigDecimal sumBigDecimalByField(List<T> list, Function<T, BigDecimal> function) {
        if (CollectionUtils.isEmpty(list)) {
            return new BigDecimal(0);
        }
        BigDecimal total = new BigDecimal(0);
        for (T t : list) {
            BigDecimal apply = function.apply(t);
            total = total.add(apply == null ? new BigDecimal(0) : apply);
        }
        return total;
    }

    public static <T, R extends Comparable> R maxByField(List<T> list, Function<T, R> function) {
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        R max = function.apply(list.get(0));
        for (int i=1,len=list.size(); i<len; i++) {
            R apply = function.apply(list.get(i));
            if (apply.compareTo(max) > 0) {
                max = apply;
            }
        }
        return max;
    }

    public static BigDecimal divide(Integer element, Integer total, int bit) {
        if (total == null || element == null || total == 0) {
            return new BigDecimal(0).setScale(bit, RoundingMode.HALF_UP);
        }
        return new BigDecimal(total).divide(new BigDecimal(element), bit, RoundingMode.HALF_UP);
    }

    public static BigDecimal divide(BigDecimal element, BigDecimal total, int bit) {
        if (total == null || element == null || new BigDecimal(0).compareTo(element) == 0) {
            return new BigDecimal(0).setScale(bit, RoundingMode.HALF_UP);
        }
        return total.divide(element, bit, RoundingMode.HALF_UP);
    }

    public static boolean notZero(BigDecimal num) {
        return null != num && BigDecimal.valueOf(0).compareTo(num) != 0;
    }

    public static boolean notZero(Integer num) {
        return null != num && !Integer.valueOf(0).equals(num);
    }

    public static void main(String[] args) {
        BigDecimal num = new BigDecimal("51015155.50");
        BigDecimal num2 = new BigDecimal("2005.00");
        BigDecimal divide = CalculateUtils.divide(num2, num, 2);
        System.out.println(divide);
        BigDecimal bigDecimal = num.divide(num2, 2, RoundingMode.HALF_UP);
        System.out.println(bigDecimal);

        int compare = new BigDecimal(0).compareTo(new BigDecimal(0.00));
        System.out.println(compare);
    }
}
